<template>
  <div>
    <el-form ref="queryForm" :model="queryParams" :inline="true">
      <el-form-item label="图片名称" prop="name">
        <el-input v-model="queryParams.imageName" placeholder="请输入参数名称" clearable></el-input>
      </el-form-item>
      <el-form-item :inline="true">
        <el-button type="primary" icon="Search" @click="handleSearch">搜索</el-button>
        <el-button icon="Refresh" @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <div>
      <el-button type="success" plain size="small" icon="Select" @click="handleSelect">反选</el-button>
      <el-button type="primary" plain size="small" icon="Plus" @click="handleAdd">新增</el-button>
      <el-button type="danger" plain size="small" icon="Delete" @click="handleDelete">删除</el-button>
    </div>
    <el-row :style="{ margin: '10px 0px' }" v-loading="loading">
      <el-col
        v-for="(o, index) in srcList.length"
        :key="o"
        :span="4"
        :offset="index === 0 || index === 5 ? 0 : 1"
        :style="{ padding: '5px 0px' }"
      >
        <el-card :body-style="{ padding: '0px' }">
          <el-image
            :src="picUrl + srcList[index].imageUrl"
            fit="contain"
            :preview-src-list="srcList.map(src => picUrl + src.imageUrl)"
            :initial-index="index"
          />
          <div style="padding: 14px">
            <el-checkbox v-model="srcList[index].selected" :label="srcList[index].imageName"></el-checkbox>
            <div class="bottom">
              <el-button type="text" class="button" @click="handleUpdate(srcList[index])">修改</el-button>
              <el-button
                type="text"
                class="copy-button"
                @click="copyUrl"
                :data-clipboard-text="srcList[index].imageUrl"
              >复制</el-button>
              <el-button type="text" class="button" @click="handleDelete(srcList[index])">删除</el-button>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <div class="pagination-block">
      <el-pagination
        layout="prev, pager, next"
        :total="total"
        :page-size="10"
        :hide-on-single-page="true"
        v-model:currentPage="queryParams.current"
        @current-change="handleCurrentChange"
      ></el-pagination>
    </div>
    <el-dialog v-model="dialogVisible" title="新增图片" width="30%">
      <div>
        <el-upload
          class="upload-demo"
          :action="upload.action"
          :headers="upload.headers"
          :multiple="false"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="imageUrl" :src="picUrl + imageUrl" class="image-item" />
          <el-icon v-else class="avatar-uploader-icon">
            <plus />
          </el-icon>
        </el-upload>
      </div>
      <el-input class="image-name" v-model="imageName" placeholder="请输入图片名称" />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleCommit">确认</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog v-model="updateVisible" title="修改名字" width="30%">
      <el-input class="image-name" v-model="imageName" placeholder="请输入图片名称" />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="updateVisible = false">取消</el-button>
          <el-button type="primary" @click="handleCommit">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue';
import Clipboard from 'clipboard'
import { getToken } from '@/utils/auth'
import { UploadFile } from 'element-plus/es/components/upload/src/upload.type';
import { add, pageList, update, deleteByIds } from '@/api/picture'
import type { Picture } from '@/api/types/picture'

const queryParams = reactive({
  imageName: undefined,
  current: 1,
  size: 10
})

const srcList = ref<Picture[]>([])

const total = ref()

const dialogVisible = ref(false)
const updateVisible = ref(false)

const imageUrl = ref()

const imageName = ref()

const picUrl = import.meta.env.VITE_SERVICE_BASE_URL

const upload = ref({
  action: import.meta.env.VITE_SERVICE_BASE_URL + '/admin/upload/sys/picture',
  headers: new Headers({
    'Authorization': "Bearer " + getToken()
  })
})

const loading = ref(false)

const updatePictureId = ref()

onMounted(() => {
  loadList()
})

/**
 * 加载列表
 */
const loadList = async () => {
  loading.value = true
  const page = await pageList(queryParams)
  srcList.value = page.records
  srcList.value.map(image => image.selected = false)
  total.value = page.total
  loading.value = false
}

/**
 * 条件查询
 */
const handleSearch = () => {
  loadList()
}

/**
 * 重置
 */
const handleReset = () => {
  queryParams.current = 1
  queryParams.size = 10
  queryParams.imageName = undefined
  loadList()
}

/**
 * 新增图片
 */
const handleAdd = () => {
  imageUrl.value = undefined
  imageName.value = undefined
  updatePictureId.value = undefined
  dialogVisible.value = true
}

/**
 * 删除
 * @param picture 
 */
const handleDelete = async (picture: Picture | any) => {
  let ids: number | number[]
  let name: string | string[]
  console.log(picture.pictureId)
  if (picture.pictureId) {
    ids = picture.pictureId
    name = picture.imageName
  } else {
    const pictures = srcList.value
    console.log(pictures)
    ids = []
    name = []
    for (let i = 0; i < pictures.length; i++) {
      if (pictures[i].selected) {
        ids.push(pictures[i].pictureId)
        name.push(pictures[i].imageName)
      }
    }
  }
  if (typeof ids !== 'number') {
    if (ids.length < 1) {
      console.log(ids)
      ElMessage({
        message: '请选择删除数据',
        type: 'error',
      })
      return
    }
  }
  try {
    await ElMessageBox.confirm(
      '是否要删除:' + name,
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    let isDelete = await deleteByIds(ids)
    if (isDelete) {
      loadList()
      ElMessage({
        message: '删除成功',
        type: 'success',
      })
    } else {
      ElMessage({
        message: '请选择删除数据',
        type: 'error',
      })
    }
  } catch (err) {

  }

}

/**
 * 反选
 */
const handleSelect = () => {
  srcList.value.map(picture => picture.selected = !picture.selected)
}

/**
 * 上传成功
 * @param response 
 * @param file 
 */
const handleAvatarSuccess = (response: string, file: UploadFile) => {
  imageUrl.value = response;
  ElMessage({
    message: '上传成功',
    type: 'success',
  })
}

/**
 * 上传前校验
 * @param file 
 */
const beforeAvatarUpload = (file: any) => {
  const isJPG = file.type === 'image/jpeg';
  const isPNG = file.type === 'image/png';
  const isLt2M = file.size / 1024 / 1024 < 5;
  if (!isJPG && !isPNG) {
    ElMessage({
      message: '上传图片只能是 JPG或PNG 格式!',
      type: 'error',
    })
  }
  if (!isLt2M) {
    ElMessage({
      message: '上传头像图片大小不能超过 5MB!',
      type: 'error',
    })
  }
  return (isJPG || isPNG) && isLt2M;
}

/**
 * 更新对话框
 * @param picture 
 */
const handleUpdate = (picture: Picture) => {
  imageName.value = picture.imageName
  updatePictureId.value = picture.pictureId
  updateVisible.value = true
}

/**
 * 复制
 */
const copyUrl = () => {
  let clipboard = new Clipboard('.copy-button')
  clipboard.on('success', e => {
    ElMessage({
      message: '复制成功',
      type: 'success',
    })
    clipboard.destroy()
  })
  clipboard.on('error', e => {
    ElMessage({
      message: '浏览器不支持复制',
      type: 'error',
    })
    clipboard.destroy()
  })
}

/**
 * 提交表单
 */
const handleCommit = async () => {
  if (updatePictureId.value && imageName.value) {
    const ok = await update(updatePictureId.value, imageName.value)
    if (ok) {
      ElMessage({
        message: '修改成功',
        type: 'success',
      })
    }
    loadList()
    updateVisible.value = false
  } else if (imageName.value === undefined || imageName.value === '') {
    ElMessage({
      message: '请填写图片名',
      type: 'error',
    })
  } else if (imageUrl.value === undefined || imageUrl.value === '') {
    ElMessage({
      message: '请像上传图片',
      type: 'error',
    })
  } else {
    const ok = await add({ imageName: imageName.value, imageUrl: imageUrl.value })
    if (ok) {
      ElMessage({
        message: '添加成功',
        type: 'success',
      })
    }
    loadList()
    dialogVisible.value = false
  }
}

const handleCurrentChange = (val: number) => {
  queryParams.current = val
  loadList()
}
</script>

<style lang="sass" scoped>

.pagination-block
  margin-top: 10px
  text-align: center

.upload-demo
  text-align: center
  border: 1px dashed #d9d9d9
  width: 80%
  margin-left: 10%
  min-height: 100px
  border-radius: 6px
  cursor: pointer
  position: relative
  overflow: hidden

.upload-demo:hover
  border-color: #409eff

.avatar-uploader-icon
  font-size: 28px
  color: #8c939d
  width: 178px
  height: 178px
  text-align: center

.image-item
  width: 100%

.image-name
  width: 80%
  margin-top: 20px
  :deep(.el-input__inner)
    text-align: center
    vertical-align: middle

:deep(.el-dialog)
  text-align: center
</style>